package com.tcppag.fixedlength;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * @author 罗俊华
 * @date 2021/8/26 - 6:08 下午
 */
@Slf4j
public class FixedLengthDecoderServer {


    /**
     * 发送和接收指定长度的消息来处理消息边界问题
     * @param args
     */
    public static void main(String[] args) {


        new ServerBootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {

                        ch.pipeline()
                                .addLast(new LoggingHandler())
                                .addLast(new FixedLengthFrameDecoder(10))
                                .addLast(new StringDecoder(StandardCharsets.UTF_8))
                                .addLast(new ChannelInboundHandlerAdapter() {
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        log.debug("接收到定长消息：{}", msg.toString());
                                    }
                                });

                    }
                }).bind(9908);
    }
}
